﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace Mimoza.UpdatePlugin
{
    class UpdateFileInstaller
    {
        public UpdateFileInstaller(string updateFileName)
        {
            m_updateFileName = updateFileName;

            Common.Logger.Log.Info("UpdateFileInstaller updateFileName - '" +
                updateFileName + "'.");
        }

        public void Install()
        {
            string imageFileName = ExtractImage();

            CopyImageFile(imageFileName);

            EraseRegistryData();

            AgentLayer.SystemPower.Reboot();

            File.Delete(imageFileName);
        }

        string ExtractImage()
        {
            string extractedFileName = m_updateFileName + ".extract";

            if (File.Exists(extractedFileName)) File.Delete(extractedFileName);

            using (FileStream extractedFile = new FileStream(extractedFileName, FileMode.CreateNew, FileAccess.Write))
            {
                using (FileStream imageFile = new FileStream(m_updateFileName, FileMode.Open, FileAccess.Read))
                {

CopyStream(imageFile, extractedFile);

/* uncomment after GZip support in utility of creating update image
                    using (GZipStream stream = new GZipStream(imageFile, CompressionMode.Decompress))
                    {
                        CopyStream(stream, extractedFile);
                    }*/
                }
            }

            return extractedFileName;
        }

        static void CopyImageFile(string imageFileName)
        {
#if WindowsCE
            string binFileName = "\\Hard Disk\\NK.bin";
            if (File.Exists(binFileName))
            {
                string saveBinFileName = binFileName + ".sav";
                if (File.Exists(saveBinFileName)) File.Delete(saveBinFileName);

                File.Move(binFileName, saveBinFileName);
            }
            File.Copy(imageFileName, binFileName, true);
#endif
        }

        void EraseRegistryData()
        {
#if WindowsCE
            const string c_DocumentSettingsPath = "Documents and Settings";
            const string c_DocumentSettingsPathSave = c_DocumentSettingsPath + ".old";
         
            try
            {
                System.IO.Directory.Delete(c_DocumentSettingsPathSave, true);
            } 
            catch(System.Exception ) {}

            System.IO.Directory.Move(c_DocumentSettingsPath, c_DocumentSettingsPathSave);
#endif
        }

        static void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[0x1000];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                output.Write(buffer, 0, read);
        }

        string m_updateFileName;
    }
}
